package sixkey.aop;

import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import sixkey.annotation.UserPermissionAnnotation;
import sixkey.domain.entity.Permiss;
import sixkey.service.IPermissService;
import sixkey.service.IUserPermissService;
import sixkey.utils.ResCodeEnum;
import sixkey.utils.ResResult;

import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName:UserPermissionAdvice
 * Package:sixkey.aop
 * Description
 *
 * @Author:@wenxueshi
 * @Create:2023/6/22 - 17:30
 * @Version:v1.0
 */
@Component
@Aspect
@Order(0)
public class UserPermissionAdvice {

    @Autowired
    private IPermissService permissService;
    @Autowired
    private IUserPermissService userPermissService;

    //切点
    @Pointcut("@annotation(sixkey.annotation.UserPermissionAnnotation)")
    public void pointcut(){};

    @Around("pointcut()")
    public Object UserPermissionAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("=============用户权限校验开始===========");
        Object[] args = joinPoint.getArgs();
        //获取登录用户的id
        String userIds = args[0].toString();
        long userId = Long.parseLong(userIds);
        //通过UserId查询权限用户对应的一个或多个权限id
        List<Integer> permissionIdList = userPermissService.getPermissIdByUserId(userId);
        //查询权限表，获取用户对应的权限
        List<Permiss> permisses = permissService.listByIds(permissionIdList);
        //获取到用户对应的权限的值
        List<String> permissions = permisses.stream().map(item -> item.getPermission()).collect(Collectors.toList());
        //获取注解对应的权限值
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //获取方法上的注解
        UserPermissionAnnotation annotation = method.getAnnotation(UserPermissionAnnotation.class);
        //获取注解的内容
        String value = annotation.value();
        boolean flag = false;
        for (String permission : permissions) {
            if(permission.equals(value)){
                flag = true;
            }
        }
        //抛出无权限异常
        if(!flag){
            return ResResult.errorResult(ResCodeEnum.NOT_PERMISSION);
        }
        return joinPoint.proceed();
    }
}
